import { ConversationList } from './conversationList.js'
import { EventTarget } from "./eventTarget.js";
import { http } from "./http.js";
import { Conversation } from './conversation.js';
import { Visitor } from './visitor.js';
import { Agent } from './agent.js';
import { ChatWindow } from './chatwindow.js';
import Cookies from './cookie.js';
export class Workbench extends EventTarget {
    constructor() {
        super();
        this.convListContainer = document.querySelector('.ss-collapse-content-box');
        this.convList = [];
        this.currentConv = null;
        this.chatWindow = new ChatWindow(null);

    }
    login(u, p) {
        http.post('/app/login', { username: u, password: p })
            .then(d => this.onLogin(JSON.parse(d)));
    }
    onLogin(d) {
        if (d.agent_uid) {
            Cookies.set("agent_uid", d.agent_uid, { expires: 1, path: '/' });
            this.initialize();
        }
    }
    onMessage(d) {
        if (d.conv) {
            var convs = this.convList.filter(x => x.id == d.conv.id);
            if (convs.length == 1) {
                var conv = convs[0];
                var m = conv.onMessage(d.message);
            }
            else {
                var conv = this.onNewConversation(d.conv);
                var m = conv.onMessage(d.message);
            }
        }
    }
    onNewConversation(d) {
        var conv = new Conversation(this, d);
        this.convList.push(conv);
        conv.getMessages(1, 20);
        var convDOM = conv.convListItemDOM();
        convDOM.addEventListener("click", () => this.onConversationSelect(conv));
        this.convListContainer.appendChild(convDOM);
        return conv;
    }
    initialize() {
        http.request(`/app/conversations`)
            .then((d) => this.initConversationList(JSON.parse(d)))
    }

    initConversationList(d) {
        d.forEach(element => {
            this.onNewConversation(element);
        });
        this.dispatchEvent({ type: 'load' });
    }

    onConversationSelect(conv) {
        console.log("onConversationSelect" + conv.id);
        if (this.currentConv == null) {
            this.currentConv = conv;
            this.currentConv.activeListItem();
        }
        else if (this.currentConv.id != conv.id) {
            this.currentConv.deactiveListItem();
            this.currentConv.chatWindowDOM().remove();
            this.currentConv = conv;
            this.currentConv.activeListItem();
        }

        if (this.currentConv != null) {
            this.chatWindow.updateConversation(this.currentConv);
            this.onConversationUpdate(conv);
        }
    }
    onConversationUpdate(conv) {
        if (this.chatWindow.conv?.id == conv.id) {
            var chatWindowDOM = this.chatWindow.dom();
            document.querySelector('main').firstElementChild.insertBefore(chatWindowDOM, document.querySelector('main').firstElementChild.firstChild)
        }
    }
}